Page({
  data: {
    files: []
  },

  onShow() {
    this.loadFiles()
  },

  loadFiles() {
    const fs = wx.getFileSystemManager()
    const userDataPath = wx.env.USER_DATA_PATH

    fs.readdir({
      dirPath: userDataPath,
      success: (res) => {
        const files = res.files
          .filter(file => file.endsWith('.csv'))
          .map(file => {
            const date = file.split('_')[1].split('.')[0]
            return {
              name: file,
              date: `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}`,
              path: `${userDataPath}/${file}`
            }
          })
          .sort((a, b) => b.date.localeCompare(a.date))

        this.setData({ files })
      },
      fail: (err) => {
        console.error('读取文件列表失败', err)
        wx.showToast({
          title: '读取文件失败',
          icon: 'none'
        })
      }
    })
  },

  handleFileTap(e) {
    const file = e.currentTarget.dataset.file
    this.previewFile(file)
  },

  handlePreview(e) {
    const file = e.currentTarget.dataset.file
    this.previewFile(file)
  },

  handleShare(e) {
    const file = e.currentTarget.dataset.file
    wx.shareFileMessage({
      filePath: file.path,
      success: () => {
        console.log('分享成功')
      },
      fail: (err) => {
        console.error('分享失败', err)
        wx.showToast({
          title: '分享失败',
          icon: 'none'
        })
      }
    })
  },

  previewFile(file) {
    const fs = wx.getFileSystemManager()
    fs.readFile({
      filePath: file.path,
      success: (res) => {
        const content = res.data
        wx.showModal({
          title: file.name,
          content: content,
          showCancel: false
        })
      },
      fail: (err) => {
        console.error('读取文件失败', err)
        wx.showToast({
          title: '读取文件失败',
          icon: 'none'
        })
      }
    })
  }
}) 